﻿
using System;
using System.Collections.Generic;
using System.Text;
using FrameWork.Lib;
using FrameWork.Lib.Diagnostics;
using FrameWork.Lib.DataObjects;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Linq;

namespace REVISIONMAX30.DataObjects
{
    public class Group : DataObjectBase
    {

        public class ExecuteSQLItemsViaBatchArgs
        {
            public List<Guid> SQLItemDataObjectGUIDList { get; set; }
            public EventManager EventManager { get; set; }
            public ExecutionType ExecutionType { get; set; }
        }

        public Group()
        {
        }

        public Group(string pGroupName)
            : base(true)
        {
            this.GroupName = pGroupName;
            this.BackUpDirectory = @".\batchtemp\";

            this.ConnectionStringList = new List<ConnectionString>();
            this.SourceDirectoryList = new List<SourceDirectory>();
            this.SQLItemList = new List<SQLItem>();

        }


        public string GroupName { get; set; }
        public int CurrentRevision { get; set; }
        public string BackUpDirectory { get; set; }


        public List<ConnectionString> ConnectionStringList { get; set; }
        public List<SourceDirectory> SourceDirectoryList { get; set; }
        public List<SQLItem> SQLItemList { get; set; }


        public Result UpdateSQLItemsFromSourceDirectories()
        {
            var tResult = new Result();
            foreach (var tSourceDirectory in this.SourceDirectoryList)
            {
                foreach (var tFile in tSourceDirectory.GetFiles())
                {

                    if (!this.SQLItemList.Exists(t => t.SourceType == "SQLFILE" && t.Source == tFile))
                    {

                        var tParseFileNameArray = tSourceDirectory.ParseFileName(tFile);

                        var tSQLItem = new DataObjects.SQLItem(tFile, "SQLFILE");

                        if (tParseFileNameArray != null)
                        {
                            tSQLItem.Revision = tParseFileNameArray[0].IntValueOrZero();
                            tSQLItem.ExecutionOrderIndex = tParseFileNameArray[1].IntValueOrZero();
                            if (tParseFileNameArray.Length >= 4)
                            {
                                tSQLItem.SourceName = tParseFileNameArray[3];
                            }

                            var tConnectionString = this.ConnectionStringList.Where(t => t.Name == tParseFileNameArray[2]).FirstOrDefault();
                            if (tConnectionString != null)
                            {
                                tSQLItem.SelectedConnectionStringGUID = tConnectionString.DataObjectGUID;
                                tSQLItem.SelectedConnectionStringName = tConnectionString.Name;
                            }
                        }

                        this.SQLItemList.Add(tSQLItem);
                    }
                }
            }
            return tResult;
        }

        public Result DumpDBsToBackUp()
        {
            var tResult = new Result();

            foreach (var tConnectionString in this.ConnectionStringList)
            {
                if (!tConnectionString.Name.Equals("temp", StringComparison.CurrentCultureIgnoreCase))
                {
                    var tFrSubResult = tConnectionString.TestConnection();

                    if (!tFrSubResult.HasErrorOrCritical())
                    {
                        var tConnectionStringBuilder = tConnectionString.ConnectionStringBuilder;

                        if (!System.IO.Directory.Exists(this.BackUpDirectory))
                        {
                            System.IO.Directory.CreateDirectory(this.BackUpDirectory);
                        }

                        string tBackUpFileName = string.Format("{0}{1}_{2}_{3}.sql", new object[] { this.BackUpDirectory, this.CurrentRevision, string.Format("{0:00}", this.ConnectionStringList.IndexOf(tConnectionString)), tConnectionStringBuilder.Database });

                        if (System.IO.File.Exists(tBackUpFileName))
                        {
                            System.IO.File.Delete(tBackUpFileName);
                        }

                        tFrSubResult = MySQLDBHandler.ExecuteDumpDBWithMySQLBatch(tConnectionStringBuilder.UserID, tConnectionStringBuilder.Password, tConnectionStringBuilder.Database, tBackUpFileName, tConnectionString.MySQLBatchPath);

                        if (tFrSubResult.HasErrorOrCritical())
                        {
                            tResult.AddResult(tFrSubResult);
                        }
                    }
                    else
                    {
                        tResult.AddResult(tFrSubResult);
                    }
                }
            }

            return tResult;
        }

        public void ExecuteSQLItems(EventManager eventManager, EventManager.DelegateAddOrUpdateItem<DataObjects.SQLItem> delegateAddOrUpdateItem, IEnumerable<SQLItem> sqlItemList)
        {
            var result = new Result();

            foreach (var sqlitem in sqlItemList)
            {
                if (sqlitem.SelectedConnectionStringGUID == null)
                {
                    result = Result.NewError("Invalid Connection String for {0}", sqlitem.SourceName);

                    sqlitem.LastExecutionResult = result;

                    eventManager.AddResult(result);
                }
                else
                {
                    var connectionstring = this.ConnectionStringList.Where(t => t.DataObjectGUID == sqlitem.SelectedConnectionStringGUID).FirstOrDefault();
                    var connectionstrinbuilder = connectionstring.ConnectionStringBuilder;

                    if (sqlitem.SourceType == "SQLFILE")
                    {
                        result = MySQLDBHandler.ExecuteSQLFileWithMySQLBatch(connectionstrinbuilder.UserID, connectionstrinbuilder.Password, connectionstrinbuilder.Database, sqlitem.Source);
                    }
                    else if (sqlitem.SourceType == "COMMANDTEXT")
                    {
                        var tempfilename = System.IO.Path.GetTempFileName();
                        System.IO.File.WriteAllText(tempfilename, sqlitem.CommandText);
                        result = MySQLDBHandler.ExecuteSQLFileWithMySQLBatch(connectionstrinbuilder.UserID, connectionstrinbuilder.Password, connectionstrinbuilder.Database, tempfilename);
                        System.IO.File.Delete(tempfilename);
                    }

                    sqlitem.LastExecutionResult = result;

                    eventManager.AddResult(result);

                    if (result.HasErrorOrCritical())
                    {
                        delegateAddOrUpdateItem(sqlitem);
                        break;
                    }
                    else
                    {
                        sqlitem.Executed = DateTime.Now;
                        delegateAddOrUpdateItem(sqlitem);
                    }
                }
            }

        }
    }
}

